import React, {useCallback, useEffect, useMemo, useState} from "react";
import {Button, Card, Collapse, Pagination, Popconfirm, Radio, Spin} from "antd";
import {getAlarmList, handleAlarm, handleAllAlarm} from "../../api/alarm";
import moment from "moment";
import AlarmCompare from "../../components/AlarmCompare";

const {Panel} = Collapse
const pageSize = 4


export default React.memo(({channelId, channelUrl}) => {

	const [currentPage, setCurrentPage] = useState(1)
	const [alarmResult, setAlarmResult] = useState()
	const [loading, setLoading] = useState(false)

	//获取警告数据
	const getAlarm = () => {
		// console.log('alarm');
		setLoading(true)
		getAlarmList({
			page_size: pageSize,
			page: currentPage,
			channel: channelId,
			result: 'N',
			order: '-occur_at'
		}).then(res => {
			// console.log(res, res.results.length);
			// console.log('render')
			setAlarmResult(res)
			setLoading(false)
		})
	}

	//翻页
	const onPageChange = useCallback((value) => {
		setCurrentPage(value)
	}, [])

	//折叠栏扩展
	const panelExtra = ({id, index}) => {
		return (
			<div onClick={e => {
				e.stopPropagation()
			}}>
				<Button type={"primary"} onClick={(event) => {
					handleAlarm({
						id,
						sample_media_url: alarmResult.results[index].sample_media_url,
						meta_media_url: alarmResult.results[index].meta_media_url
					}).then(res => {
						getAlarm()
					})
				}}>
					处理
				</Button>
			</div>
		)
	}

	useEffect(getAlarm, [channelId, currentPage])


	return (
		<Spin spinning={loading} size={'large'} tip={'数据加载中'}>
			<>
				<Collapse>
					{
						alarmResult?.results.map((item, index) => {
							return (
								<Panel key={item.id}
								       header={`异常时间:${moment(item.occur_at).format("yyyy-MM-DD HH:mm:ss")}`}
								       extra={panelExtra({id: item.id, index})}>
									<AlarmCompare item={item}/>
								</Panel>
							)
						})
					}
				</Collapse>
				<div style={{display: "flex", justifyContent: "space-between", alignItems: "flex-end"}}>
					<Pagination
						style={{marginTop: '20px'}}
						pageSize={pageSize}
						total={alarmResult?.count}
						onChange={onPageChange}
						current={currentPage}
					/>
					<Popconfirm title={"确认处理全部异常吗？"} onConfirm={() => {
						// console.log(channelUrl);
						handleAllAlarm(channelUrl, 'C').then(getAlarm)
					}}>

						<Button type={"danger"}>处理全部</Button>
					</Popconfirm>
				</div>

			</>
		</Spin>
	)
})
